<template>
  <div>
    <!-- 导航区域 -->
    <el-breadcrumb
      class="usersBreadcrumb"
      separator="/"
    >
      <el-breadcrumb-item :to="{ path: '/users' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户信息区域</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click='getUserList'
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click='addDialogVisible=true'
          >添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 添加用户弹窗区域 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <el-form
          :model="addUserInfo"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="70px"
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input v-model='addUserInfo.username'>1</el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
          >
            <el-input v-model="addUserInfo.password">2</el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="addUserInfo.email"> 3</el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="mobile"
          >
            <el-input v-model="addUserInfo.mobile">4</el-input>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            @click="addUser"
          >确 定</el-button>
          <el-button @click="addDialogVisible = false">取 消</el-button>

        </span>
      </el-dialog>

      <!-- 分配用户角色弹窗区域 -->
      <el-dialog
        title="分配用户角色"
        :visible.sync="setUserRoledialogVisible"
        width="50%"
        @close="closeRolesDialog"
      >
        <p>当前的用户:{{userRolesInfo.username}}</p>
        <p>当前的用户角色:{{userRolesInfo.role_name}}</p>
        <div>
          <span class='rolesSelect'>分配角色</span>
          <template>
            <el-select
              v-model="roleValue"
              placeholder="请选择"
            >
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </template>
        </div>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="setUserRoledialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="saveUserRole()"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户信息弹窗区域 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClose"
      >
        <el-form
          :model="editUserInfo"
          :rules="addFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input
              v-model='editUserInfo.username'
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="editUserInfo.email"></el-input>
          </el-form-item>
          <el-form-item
            label="手机号"
            prop="mobile"
          >
            <el-input v-model="editUserInfo.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button
            type="primary"
            @click="editDialogPut"
          >确 定</el-button>
          <el-button @click="editDialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
      <!-- 用户信息区域 -->
      <el-table
        :data="userlist"
        border
        stripe
      >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          label="姓名"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
        ></el-table-column>
        <el-table-column
          label="电话"
          prop="mobile"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
        ></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userInfoChange(userlist)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
        >
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editDialogChanged(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUserInfo(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setUserRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pageszie"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]))/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('邮箱格式错误'))
    }
    var checkmobile = (rule, value, cb) => {
      const regmobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regmobile.test(value)) {
        return cb()
      }
      cb(new Error('联系方式格式错误'))
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      userlist: [],
      total: 0,
      // 控制添加用户弹窗显示与否
      addDialogVisible: false,
      // 控制修改用户信息弹窗显示与否
      editDialogVisible: false,
      addUserInfo: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserInfo: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 控制分配用户角色弹窗显示与否
      setUserRoledialogVisible: false,
      userRolesInfo: [],
      rolesList: [],
      roleValue: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        // console.log(res)
        return this.$message.error('请求参数失败')
      }
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    handleSizeChange (newsize) {
      this.queryInfo.pagesize = newsize
      this.getUserList()
    },
    handleCurrentChange (newcurrent) {
      this.queryInfo.pagenum = newcurrent
      this.getUserList()
    },
    async userInfoChange (userlist) {
      // console.log(userlist[0].id)
      const { data: res } = await this.$http.put(`users/${userlist[0].id}/state/${userlist[0].mg_state}`)
      // console.log(userlist[0].id)
      // console.log(res)
      if (res.meta.status !== 200) {
        userlist[0].mg_state = !userlist[0].mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新成功')
      // console.log(userlist[0].mg_state)
    },
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('添加失败')
        const { data: res } = await this.$http.post('users', this.addUserInfo)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    async editDialogChanged (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`users/${id}`)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.editUserInfo.username = res.data.username
      this.editUserInfo.mobile = res.data.mobile
      this.editUserInfo.email = res.data.email
      this.editUserInfo.id = res.data.id
    },
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    editDialogPut () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('格式错误')
        console.log(this.editUserInfo.id)
        const { data: res } = await this.$http.put(`users/${this.editUserInfo.id}`, this.editUserInfo)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('添加失败')
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    async deleteUserInfo (id) {
      const confirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '警告！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm !== 'confirm') return this.$message.info('已取消')
      // console.log(confirm)
      // console.log(id)
      const { data: res } = await this.$http.delete(`users/${id}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUserList()
    },
    // 打开分配角色弹窗 并且获取该角色ID和所有可选角色列表
    async setUserRole (info) {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      this.rolesList = res.data
      // console.log(this.rolesList)
      this.userRolesInfo = info
      // console.log(this.userRolesInfo)
      this.setUserRoledialogVisible = true
    },
    // 点击确定保存用户角色信息
    async saveUserRole () {
      if (!this.roleValue) return this.$message.error('请选择新的角色')
      const { data: res } = await this.$http.put(`users/${this.userRolesInfo.id}/role`, { rid: this.roleValue })
      if (res.meta.status !== 200) return this.$message.error('设置失败')
      this.$message.success('设置成功！')
      this.setUserRoledialogVisible = false
    },
    // 分配角色弹窗关闭时清空data中 的角色ID 和所有可选角色列表
    closeRolesDialog () {
      this.userRolesInfo = []
      this.roleValue = ''
    }
  }
}
</script>

<style scoped>
@import url(../../../assets/css/users.css);
</style>
